import {pinyin} from "pinyin-pro";

// 拼音匹配函数
export const matchesPinyin = (text: string, keyword: string) => {
    if (!text || !keyword) return false;

    const lowerText = text.toLowerCase();
    const lowerKeyword = keyword.toLowerCase();

    // 直接匹配（中文、英文、数字）
    if (lowerText.includes(lowerKeyword)) return true;

    try {
        // 获取完整拼音（连续，无空格）
        const fullPinyin = pinyin(text, {toneType: "none", type: "string"})
            .toLowerCase()
            .replace(/\s+/g, "");

        // 完整拼音匹配（如：zhongshan 匹配 中山）
        if (fullPinyin.includes(lowerKeyword)) return true;

        // 获取首字母（连续，无空格）
        const initials = pinyin(text, {pattern: "first", toneType: "none", type: "string"})
            .toLowerCase()
            .replace(/\s+/g, "");
        if (initials.includes(lowerKeyword)) return true;

        // 分词拼音匹配（如：zhong 或 shan 匹配 中山）
        const pinyinArray = pinyin(text, {type: "array", toneType: "none"});
        for (const py of pinyinArray) {
            if (py.toLowerCase().includes(lowerKeyword)) return true;
        }

        // 逐字符处理首字母匹配
        let charInitials = "";
        for (const char of text) {
            try {
                if (/[\u4e00-\u9fa5]/.test(char)) {
                    // 中文字符
                    const initial = pinyin(char, {pattern: "first", toneType: "none", type: "string"});
                    charInitials += initial.toLowerCase();
                } else {
                    charInitials += char.toLowerCase();
                }
            } catch {
                charInitials += char.toLowerCase();
            }
        }
        if (charInitials.includes(lowerKeyword)) return true;

        // 混合匹配模式：支持拼音和首字母混用
        // 例如："bj大学" 可以匹配 "北京大学"
        const mixedPattern = lowerKeyword;
        let textIndex = 0;
        let keywordIndex = 0;

        while (textIndex < text.length && keywordIndex < mixedPattern.length) {
            const char = text[textIndex];

            if (/[\u4e00-\u9fa5]/.test(char)) {
                // 中文字符
                const charPinyin = pinyin(char, {toneType: "none", type: "string"}).toLowerCase();
                const charInitial = pinyin(char, {pattern: "first", toneType: "none", type: "string"}).toLowerCase();

                // 尝试匹配完整拼音
                if (charPinyin.startsWith(mixedPattern.substring(keywordIndex))) {
                    keywordIndex += charPinyin.length;
                }
                // 尝试匹配首字母
                else if (charInitial === mixedPattern[keywordIndex]) {
                    keywordIndex += 1;
                }
                // 尝试部分拼音匹配
                else {
                    let matchedLength = 0;
                    for (let i = 1; i <= charPinyin.length && keywordIndex + i <= mixedPattern.length; i++) {
                        if (charPinyin.startsWith(mixedPattern.substring(keywordIndex, keywordIndex + i))) {
                            matchedLength = i;
                        }
                    }
                    if (matchedLength > 0) {
                        keywordIndex += matchedLength;
                    }
                }
            } else {
                // 非中文字符直接匹配
                if (char.toLowerCase() === mixedPattern[keywordIndex]) {
                    keywordIndex += 1;
                }
            }

            textIndex += 1;
        }

        if (keywordIndex >= mixedPattern.length) return true;
    } catch (error) {
        console.warn("拼音匹配失败:", error);
    }

    return false;
};

// 高亮关键词函数
export const highlightKeyword = (text: string, keyword: string) => {
    if (!text || !keyword) return text;

    const lowerText = text.toLowerCase();
    const lowerKeyword = keyword.toLowerCase();

    // 直接匹配高亮
    if (lowerText.includes(lowerKeyword)) {
        const regex = new RegExp(`(${keyword})`, "gi");
        return text.replace(regex, '<span class="text-red-500">$1</span>');
    }

    try {
        // 拼音匹配 - 精确定位匹配的字符
        const fullPinyin = pinyin(text, {toneType: "none", type: "string"})
            .toLowerCase()
            .replace(/\s+/g, "");

        if (fullPinyin.includes(lowerKeyword)) {
            return highlightPinyinMatch(text, keyword, "full");
        }

        // 首字母匹配 - 精确定位匹配的字符
        const initials = pinyin(text, {pattern: "first", toneType: "none", type: "string"})
            .toLowerCase()
            .replace(/\s+/g, "");

        if (initials.includes(lowerKeyword)) {
            return highlightPinyinMatch(text, keyword, "initial");
        }

        // 逐字符首字母匹配
        let charInitials = "";
        for (const char of text) {
            try {
                if (/[\u4e00-\u9fa5]/.test(char)) {
                    const initial = pinyin(char, {pattern: "first", toneType: "none", type: "string"});
                    charInitials += initial.toLowerCase();
                } else {
                    charInitials += char.toLowerCase();
                }
            } catch {
                charInitials += char.toLowerCase();
            }
        }
        if (charInitials.includes(lowerKeyword)) {
            return highlightPinyinMatch(text, keyword, "char-initial");
        }

        // 分词拼音匹配
        const pinyinArray = pinyin(text, {type: "array", toneType: "none"});
        for (const py of pinyinArray) {
            if (py.toLowerCase().includes(lowerKeyword)) {
                return highlightPinyinMatch(text, keyword, "partial");
            }
        }
    } catch (error) {
        console.warn("拼音高亮失败:", error);
    }

    return text;
};

// 精确高亮拼音匹配的字符
const highlightPinyinMatch = (text: string, keyword: string, matchType: string) => {
    const lowerKeyword = keyword.toLowerCase();
    let result = "";
    let keywordIndex = 0;
    let highlightBuffer = ""; // 缓存连续的高亮字符
    let normalBuffer = ""; // 缓存连续的普通字符

    const flushBuffers = () => {
        if (normalBuffer) {
            result += normalBuffer;
            normalBuffer = "";
        }
        if (highlightBuffer) {
            result += `<span class="text-red-500">${highlightBuffer}</span>`;
            highlightBuffer = "";
        }
    };

    for (let i = 0; i < text.length; i++) {
        const char = text[i];
        let shouldHighlight = false;

        if (/[\u4e00-\u9fa5]/.test(char)) {
            // 中文字符
            try {
                let charPattern = "";
                switch (matchType) {
                    case "full":
                        charPattern = pinyin(char, {toneType: "none", type: "string"}).toLowerCase();
                        break;
                    case "initial":
                    case "char-initial":
                        charPattern = pinyin(char, {pattern: "first", toneType: "none", type: "string"}).toLowerCase();
                        break;
                    case "partial":
                        charPattern = pinyin(char, {toneType: "none", type: "string"}).toLowerCase();
                        break;
                }

                // 检查是否匹配当前关键词位置
                if (keywordIndex < lowerKeyword.length) {
                    if (matchType === "initial" || matchType === "char-initial") {
                        // 首字母匹配：只要首字母对应就高亮
                        if (charPattern === lowerKeyword[keywordIndex]) {
                            shouldHighlight = true;
                            keywordIndex++;
                        }
                    } else {
                        // 完整拼音匹配：检查是否匹配拼音的开始部分
                        const remainingKeyword = lowerKeyword.substring(keywordIndex);
                        if (remainingKeyword.startsWith(charPattern)) {
                            shouldHighlight = true;
                            keywordIndex += charPattern.length;
                        } else if (charPattern.startsWith(remainingKeyword)) {
                            shouldHighlight = true;
                            keywordIndex = lowerKeyword.length;
                        }
                    }
                }
            } catch {
                // 如果拼音转换失败，按字符匹配
                if (keywordIndex < lowerKeyword.length && char.toLowerCase() === lowerKeyword[keywordIndex]) {
                    shouldHighlight = true;
                    keywordIndex++;
                }
            }
        } else {
            // 非中文字符直接匹配
            if (keywordIndex < lowerKeyword.length && char.toLowerCase() === lowerKeyword[keywordIndex]) {
                shouldHighlight = true;
                keywordIndex++;
            }
        }

        if (shouldHighlight) {
            // 如果有普通字符缓存，先输出
            if (normalBuffer) {
                result += normalBuffer;
                normalBuffer = "";
            }
            // 添加到高亮缓存
            highlightBuffer += char;
        } else {
            // 如果有高亮字符缓存，先输出
            if (highlightBuffer) {
                result += `<span class="text-red-500">${highlightBuffer}</span>`;
                highlightBuffer = "";
            }
            // 添加到普通缓存
            normalBuffer += char;
        }
    }

    // 处理剩余的缓存
    flushBuffers();

    return result;
};
